package com.wiz.netty;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.wiz.data.vo.to.DataMessageTemplate;
import com.wiz.data.vo.to.MessageFiled;

/**
 * wiz数据格式模板解析
 * @author Hakeny
 */
public class NettyXmlParseFactory {
	private String fileurl;
	private Map<String, DataMessageTemplate> paramMap;

	@SuppressWarnings("unchecked")
	public void init() throws Exception {
		URL url = NettyXmlParseFactory.class.getResource("/");
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(url.getPath()+fileurl));
		Element root = document.getRootElement();
		Iterator<Element> itRoot = root.elementIterator();
		paramMap = new HashMap<String,DataMessageTemplate>();
		while(itRoot.hasNext()){
			Element paramNode = itRoot.next();//解读到 param位置
			String messageName = paramNode.attribute("name").getText();
			DataMessageTemplate dm = new DataMessageTemplate();
			Iterator<Element> it = paramNode.elementIterator();
			while(it.hasNext()){//解析每个数据
				Element elementFiled = it.next();//解读到filed位置
				String index = elementFiled.attributeValue("index");
				String className = elementFiled.attributeValue("className");
				String needLength = elementFiled.attributeValue("needLength");
				MessageFiled filed = (MessageFiled) Class.forName(className).newInstance();
				filed.setIndex(Integer.parseInt(index));
				filed.setNeedLength(needLength == null?0:Integer.parseInt(needLength));
//				filed.setType(type);
				dm.addMessageFiled(index,filed);
			}
			paramMap.put(messageName, dm);
		}
	}
	
	/**
	 * 获得初始化后的消息模板副本
	 * @param messageName
	 * @return
	 * @throws CloneNotSupportedException
	 */
	public DataMessageTemplate getDataMessageTemplate(String messageName) throws CloneNotSupportedException{
		DataMessageTemplate dm = paramMap.get(messageName);
		return (DataMessageTemplate) dm.clone();
	}

	public String getFileurl() {
		return fileurl;
	}

	public void setFileurl(String fileurl) {
		this.fileurl = fileurl;
	}

}
